<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('指标年度')" prop="indicatorYear">
            <DatePicker v-model="form.indicatorYear" type="year" value-format="yyyy" :placeholder="$t('年')" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title"><i style="color: #ff4949;margin-right: 4px;font-weight: 300;font-size: 14px;">*</i>{{ $t('项目列表') }}</span>
      </div>
      <el-row>
        <el-tag
          v-for="(item, i) in dealListTag"
          :key="item.companyId"
          closable
          :effect="i === index ? 'plain' : 'light'"
          :type="i === index ? 'info' : 'info'"
          style="margin-right: 10px;cursor:pointer;margin-bottom: 5px;"
          @click="clickHandle(i)"
          @close="closeHandle(item)"
        >
          {{ item.companyName }}
        </el-tag>
        <el-button
          v-hasPermi="['deal:indicators:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="showDealListHandle"
        >{{ $t("新增") }}</el-button>
      </el-row>
      <div v-if="dealListTag && dealListTag.length > 0" class="area-header" style="margin-top: 10px;">
        <span class="area-header-title">{{ $t('指标维护明细') }}</span>
      </div>
      <el-table v-if="dealListTag && dealListTag.length > 0" v-loading="maintainDetailLoading" :data="form.dealIndicatorBatchDetailsList[index] && form.dealIndicatorBatchDetailsList[index].dealIndicatorsMaintainDetailsList ? form.dealIndicatorBatchDetailsList[index].dealIndicatorsMaintainDetailsList : form.dealIndicatorBatchDetailsList[0].dealIndicatorsMaintainDetailsList" border class="nowrapTable formTable">
        <el-table-column :label="$t('指标名称')" align="center" prop="indicatorName" show-overflow-tooltip>
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('指标名称') }}</span>
          </template>
          <template slot-scope="scope">
            <el-input v-model="scope.row.indicatorName" show-word-limit :maxlength="100" :placeholder="$t('指标名称')" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('指标方向')" align="center" prop="indicatorDirection">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('指标方向') }}</span>
          </template>
          <template slot-scope="scope">
            <el-select v-model="scope.row.indicatorDirection" :placeholder="$t('指标方向')">
              <el-option
                v-for="(item, index) in indicatorDirectionOptions"
                :key="index"
                :value="item.dictValue"
                :label="$t(item.dictLabel)"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column :label="$t('年报目标值(万/百分比/个)')" align="center" prop="targetValue">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('年报目标值(万/百分比/个)') }}</span>
          </template>
          <template slot-scope="scope">
            <money v-model="scope.row.targetValue" :placeholder="$t('年报目标值')" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('备注')" align="center" prop="remark">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" type="textarea" :placeholder="$t('备注')" show-word-limit :maxlength="2000" :autosize="{ minRows: 2, maxRows: 4}" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="80">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="delIndicatorsMaintainDetail(scope.$index)">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="dealListTag && dealListTag.length > 0" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addIndicatorsMaintainDetail">{{ $t("添加") }}</el-button>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <save-btn has-permi="deal:indicators" />
    </div>
    <!-- 添加或修改指标维护对话框 -->
    <el-dialog :title="$t('项目列表')" :visible.sync="dealListOpen" :close-on-click-modal="false" :lock-scroll="false" width="70%" append-to-body @opened="dealListOpenHandle">
      <div class="list-table" style="padding:0;box-shadow:none;">
        <el-form ref="dealListQuery" :model="dealListQuery" :inline="true">
          <el-form-item :label="$t('项目名称')" prop="dealName">
            <el-input v-model="dealListQuery.dealName" :placeholder="$t('项目名称')" />
          </el-form-item>
          <el-form-item :label="$t('项目负责人')" prop="personCharge">
            <user-select v-model="dealListQuery.personCharge" :placeholder="$t('项目负责人')" />
          </el-form-item>
          <el-form-item :label="$t('资产评级')" prop="latestAssetRating">
            <dict-select
              v-model="dealListQuery.latestAssetRating"
              dictionary="current_rating_type"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table ref="dealListTable" v-loading="dealListLoading" max-height="500" :data="dealList" :span-method="objectSpanMethod" row-key="dealId" border @select="handleSelectionChange" @select-all="handleSelectionChange">
        <el-table-column type="selection" align="center" width="55" :reserve-selection="true" />
        <el-table-column :label="$t('标的公司名称')" align="center" prop="companyName" />
        <el-table-column :label="$t('项目名称')" align="center" prop="dealName" />
        <el-table-column :label="$t('项目负责人')" align="center" prop="personChargeName" />
      </el-table>
      <div style="margin: 15px 0 0; text-align:right;">
        <el-button icon="el-icon-check" type="primary" size="mini" @click="dealListOpen = false">{{ $t("确认") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import { saveBatch } from '@/api/deal/operational/maintain/dealIndicatorsMaintain'
    import { getDealIndicatorBatch, findAfterDealListByScope } from '@/api/deal/operational/batch/dealIndicatorBatch'
    export default {
      data() {
            return {
              // 是否隐藏保存按钮
              btnHide: false,
              // 是否显示项目列表
              dealListOpen: false,
              // 项目列表遮罩层
              dealListLoading: false,
              // 数量
              dealListTotal: 0,
              // 项目列表查询参数
              dealListQuery: {
                dealName: undefined,
                personCharge: undefined,
                latestAssetRating: undefined,
                pageNum: 1,
                pageSize: 10
              },
                // 表单参数
                form: {
                  dealIndicatorBatchDetailsList: [
                    { dealIndicatorsMaintainDetailsList: [] }
                  ]
                },
                // 遮罩层
                loading: false,
              dealList: [],
              dealListTag: [],
              wait: true,
              // 指标维护明细遮罩层
              maintainDetailLoading: false,
              // 指标方向
              indicatorDirectionOptions: [],
              companyId: this.$route.query.companyId,
              index: 0,
              // 表单校验
              rules: {
                indicatorYear: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], lastYearAssetRating: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], actTitle: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ]
              },
              indicatorsMaintainDetailRules: {
                indicatorName: { required: true, message: this.$t('必填信息'), trigger: 'blur' },
                indicatorDirection: { required: true, message: this.$t('必填信息'), trigger: 'blur' },
                targetValue: { required: true, message: this.$t('必填信息'), trigger: 'blur' }
              }
            }
        },
        created() {
          this.getDicts('indicator_direction').then(response => {
            this.indicatorDirectionOptions = response.data
          })
          this.$bus.$emit('async_done')
        },
        methods: {
            // 初始化数据
            init(data) {
              this.loading = true
              this.index = 0
              if (data != null && data.id !== undefined) {
                this.wait = true
                if (this.$refs.dealListTable) {
                  this.$refs.dealListTable.clearSelection()
                }
                getDealIndicatorBatch(data.id).then(response => {
                  this.dealListTag = response.data.dealIndicatorBatchDetailsList
                  this.form = response.data
                  this.loading = false
                })
              } else {
                this.reset()
                if (this.$refs.dealListTable) {
                  this.$refs.dealListTable.clearSelection()
                }
                this.loading = false
              }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                indicatorYear: undefined,
                lastYearAssetRating: undefined,
                personCharge: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                actTitle: undefined,
                dealIndicatorBatchDetailsList: [
                  { dealIndicatorsMaintainDetailsList: [] }
                ]
                }
                this.resetForm('form')
              this.dealListTag = []
              this.index = 0
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                      if (this.dealListTag.length === 0) {
                        this.$message({
                          type: 'warning',
                          message: this.$t('最少维护一个项目指标')
                        })
                        return
                      }
                        this.loading = true
                        let flag = true
                        this.form.dealIndicatorBatchDetailsList.forEach((ele, index) => {
                          if (ele.dealIndicatorsMaintainDetailsList && ele.dealIndicatorsMaintainDetailsList.length > 0) {
                            ele.dealIndicatorsMaintainDetailsList.forEach((item) => {
                              if (!(item.indicatorName && item.indicatorDirection && item.targetValue)) {
                                if (flag) {
                                  this.$message({
                                    type: 'warning',
                                    message: this.form.dealIndicatorBatchDetailsList[index].companyName + this.$t('有必填信息没有填写')
                                  })
                                  flag = false
                                }
                              }
                            })
                          } else {
                            if (flag) {
                              this.$message({
                                type: 'warning',
                                message: this.form.dealIndicatorBatchDetailsList[index].companyName + this.$t('还没有维护指标')
                              })
                              flag = false
                            }
                          }
                        })
                        if (!flag) {
                          this.loading = false
                          return
                        }
                      saveBatch(this.form).then(response => {
                        if (response.code === 200) {
                          this.msgSuccess(this.$t('保存成功'))
                          this.closeForm()
                        } else {
                          this.msgError(response.msg)
                        }
                        this.loading = false
                      })
                    } else {
                      this.locationError(document)
                    }
                })
           },
          // 删除指标明细
          delIndicatorsMaintainDetail(index) {
              this.form.dealIndicatorBatchDetailsList[this.index].dealIndicatorsMaintainDetailsList.splice(index, 1)
          },
          // 添加指标明细
          addIndicatorsMaintainDetail() {
            const row = {
              id: undefined,
              maintainId: undefined,
              indicatorName: undefined,
              indicatorDirection: undefined,
              targetValue: undefined,
              remark: undefined
            }
            if (!(this.form.dealIndicatorBatchDetailsList[this.index].dealIndicatorsMaintainDetailsList instanceof Array)) {
              this.$set(this.form.dealIndicatorBatchDetailsList[this.index], 'dealIndicatorsMaintainDetailsList', [])
            }
            this.$nextTick(() => {
              this.form.dealIndicatorBatchDetailsList[this.index].dealIndicatorsMaintainDetailsList.push(row)
            })
          },
          clickHandle(index) {
            this.index = index
          },
          closeHandle(item) {
            this.dealListTag = this.dealListTag.filter((e) => e.companyId !== item.companyId)
            this.$refs.dealListTable.store.states.selection = this.dealListTag
            this.$refs.dealListTable.store.updateSelectionByRowKey() // 重新计算selection
            this.$refs.dealListTable.store.updateAllSelected() // 计算全选
            this.form.dealIndicatorBatchDetailsList = this.form.dealIndicatorBatchDetailsList.filter((e) => e.companyId !== item.companyId)
            if (this.form.dealIndicatorBatchDetailsList.length === 0) {
              this.form.dealIndicatorBatchDetailsList = [{ dealIndicatorsMaintainDetailsList: [] }]
            }
          },
          // 展示项目列表
          showDealListHandle() {
            if (this.form.indicatorYear) {
              this.dealListOpen = true
              if (!this.dealList || this.dealList.length === 0) {
                this.queryHandle()
              }
            } else {
              this.$message({
                type: 'warning',
                message: this.$t('请先选择指标年度')
              })
            }
          },
          getList() {
            this.dealListQuery.year = this.form.indicatorYear
            findAfterDealListByScope(this.dealListQuery).then(res => {
              this.dealList = res.rows
              this.dealListLoading = false
            })
          },
          queryHandle() {
            this.dealListQuery.pageNum = 1
            this.getList()
            this.dealListLoading = true
            this.$nextTick(() => {
              if (!this.dealListTag || this.dealListTag.length === 0) {
                this.$refs.dealListTable.clearSelection()
              }
            })
          },
          resetQuery() {
            this.resetForm('dealListQuery')
            this.queryHandle()
          },
          // 项目列表复选框事件
          handleSelectionChange(rows) {
            this.index = 0
            this.dealListTag = this.form.dealIndicatorBatchDetailsList = rows
            if (rows.length === 0) {
              this.form.dealIndicatorBatchDetailsList = [{ dealIndicatorsMaintainDetailsList: [] }]
            }
          },
          dealListOpenHandle() {
            this.$nextTick(() => {
              if (this.form.id) {
                for (let i = 0; i < this.dealList.length; i++) {
                  this.dealListTag.forEach((item) => {
                    if (this.dealList[i].companyId === item.companyId) {
                      this.$refs.dealListTable.toggleRowSelection(this.dealList[i], true)
                    }
                  })
                }
                this.wait = false
              }
            })
          },
          objectSpanMethod({ rowIndex, columnIndex }) {
            if (columnIndex === 0 || columnIndex === 1) {
              const spanArr = this.rowspan()
              for (let i = 0; i < spanArr.length; i++) {
                const _row = spanArr[rowIndex]
                return {
                  rowspan: _row,
                  colspan: 1
                }
              }
            }
          },
          rowspan() {
            // 二维数组，用于存放单元格合并规则
            const spanArr = []
            // 用于存储相同项的开始index
            let position = 0
            this.dealList.forEach((item, index) => {
              if (index === 0) {
                spanArr.push(1)
                position = 0
              } else {
                if (this.dealList[index].companyId === this.dealList[index - 1].companyId) {
                  spanArr[position] += 1 // 有相同项
                  spanArr.push(0) // 名称相同后往数组里面加一项0
                } else {
                  spanArr.push(1) // 同列的前后两行单元格不相同
                  position = index
                }
              }
            })
            return spanArr
          }
        }
    }
</script>

<style scoped>
</style>
